package com.amsp.oa.oademo.service.impl;

import com.amsp.oa.oademo.entity.FormControl;
import com.amsp.oa.oademo.mapper.FormControlMapper;
import com.amsp.oa.oademo.service.FormControlService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class FormControlServiceImpl implements FormControlService {

    @Resource
    private FormControlMapper formControlMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<FormControl> formControls) {
        for (FormControl formControl : formControls) {
            if (formControl.getId() != null) {
                formControlMapper.updateById(formControl);
            } else {
                formControlMapper.insert(formControl);
            }
        }
    }

    @Override
    public FormControl getById(Long id) {
        return formControlMapper.selectById(id);
    }

    @Override
    public IPage<FormControl> getList(Page<FormControl> page, String keyword) {
        LambdaQueryWrapper<FormControl> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            wrapper.like(FormControl::getFormName, keyword)
                    .or()
                    .like(FormControl::getFormNumber, keyword)
                    .or()
                    .like(FormControl::getProductionDepartment, keyword);
        }
        wrapper.orderByDesc(FormControl::getCreateTime);
        return formControlMapper.selectPage(page, wrapper);
    }

    @Override
    public void deleteById(Long id) {
        formControlMapper.deleteById(id);
    }
}